//
//  NotificationListViewController.m
//  MapLink
//
//  Created by heng zhang on 21/05/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NotificationListViewController.h"
#import "NotificationEntity.h"
#import "NotificationGroupMapViewController.h"
#import "JSON/JSON.h"
#import "EntityManager.h"
#import "NetworkManager.h"
#import "NotificationEntity.h"
#import "sqlite3.h"
#import "NotificationCell.h"


@implementation NotificationListViewController

@synthesize deviceID,groupName,userName,newNotifications,buffer;

- (id) init {
	[super initWithNibName:@"NotificationListViewController" bundle:nil];
	[[self navigationItem] setTitle:@"Notifications"];
	
	return self;
}

- (id) initWithDeviceID:(NSString *)strDeviceID withUserName:(NSString *)strUserName withGroupName:(NSString *) strGroupName withNumberOfNotifications:(int) number{
	self = [self init];
	self.deviceID = strDeviceID;
	self.userName = strUserName;
	self.groupName = strGroupName;
	self.newNotifications = number;
	[self loadNotificationsFromDB];
	return self;
}

-(IBAction) cancel {
	NSLog(@"cancel");
	[self dismissModalViewControllerAnimated:YES];
}

- (void)viewDidLoad {
	[super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
}

- (void) viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[self refreshData];
}

- (void) loadNotificationsFromDB {
	[EntityManager copyDatabaseIfNeeded];   // check and copy SQL.lite file to Documents folder for use
	EntityManager *entityMgr = [[EntityManager alloc] init];
	
	if (notifications) {
		[notifications release];
	}
	notifications = [entityMgr getNotificationList:groupName];
	[notifications retain];
	
	[entityMgr release];
}

- (void) refreshData {
	NSString *strRequest = @"http://mybuddies.emiu.net/getmessage.php?device_id=%@&name=%@&group=%@";
	
	NSString *urlString = [NSString stringWithFormat:strRequest,
						   [deviceID stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
						   [userName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
						   [groupName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
	NSURL *url = [NSURL URLWithString:urlString];
	NSLog(@"URL:%@",urlString);
	
	if (![NetworkManager connectedToNetwork]) {
		return;
	}
	
	[activityIndicatorView startAnimating];

	if(!url) {
		// error in creating NSURL object
	} else {
		NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
		if (!req) {
			// error in creating Request object
		} else {
			[req setHTTPMethod:@"GET"];
			/* Synchronous request */
			/*
			NSURLResponse *response;
			NSError *error;
			NSData *result = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
			self.buffer = [NSMutableData dataWithData:result];
			[self processData:buffer];
			 */
			/* Asynchronous request */
			conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
			if (conn) {
				self.buffer = [NSMutableData data]; 
			}
		}
	}
	
	[notificationTableView reloadData];
	[activityIndicatorView stopAnimating];
}

- (void) processData:(NSMutableData *)data {
	if (!data) return;
	NSMutableString *jsonString = [[NSMutableString alloc] initWithBytes:[data mutableBytes]
																  length:[data length]
																encoding:NSUTF8StringEncoding];
	NSDictionary *response = [jsonString JSONValue];
	NSString *result = [response objectForKey:@"result"];
	NSString *error = [response objectForKey:@"message"];
		
	if ([result isEqualToString:@"Y"]) {
		// Successful insert into local database
		NSLog(@"JSON:%@", jsonString);
		[EntityManager copyDatabaseIfNeeded];   // check and copy SQL.lite file to Documents folder for use
		EntityManager *entityMgr = [[EntityManager alloc] init];
		
		NSArray *records = [response objectForKey:@"notifications"];
		NSMutableArray *newData = [[NSMutableArray alloc] init];
		int count = 0;
		for (NSDictionary *record in records) {
			NotificationEntity *entity = [NotificationEntity alloc];
			entity.userName = [record valueForKey:@"sender"];
			entity.deviceId = [record valueForKey:@"device_id"];
			entity.groupName = [record valueForKey:@"group"];
			entity.locationX = [NSDecimalNumber decimalNumberWithString:[record valueForKey:@"latitude"]];
			entity.locationY = [NSDecimalNumber decimalNumberWithString:[record valueForKey:@"longitude"]];
			entity.createDate = [record valueForKey:@"time"];
			entity.notificationMsg = [record valueForKey:@"message"];
			[entityMgr addNotification:entity];
			[newData addObject:[NSIndexPath indexPathForRow:0 inSection:0]];
			count++;
			[entity release];
		}
		[notificationTableView beginUpdates];
		[notificationTableView insertRowsAtIndexPaths:newData withRowAnimation:UITableViewRowAnimationNone];
		[self loadNotificationsFromDB];
		[notificationTableView endUpdates];
		[notificationTableView reloadData];
		[newData release];
		[entityMgr release];
	} else {
		// Error
		NSLog(@"ERROR: %@", error);
	}
	
	//[self loadNotificationsFromDB];
	
	[jsonString release];
}

/* START: Connection delegate */
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
	[buffer setLength:0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
	[buffer appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
	[buffer release];
	[connection release];
	[activityIndicatorView stopAnimating];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
	NSLog(@"Done with bytes %d", [buffer length]);
	[self processData:buffer];
	[activityIndicatorView stopAnimating];

	[connection release];
}
/* END: Connection delegate */

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	return [notifications count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"NotificationCell";
    /*
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    NotificationEntity *noti = [notifications objectAtIndex:[indexPath row]];
	cell.imageView.image = [UIImage imageNamed:@"profile.png"];
	cell.textLabel.text = [NSString stringWithFormat:@"%@   (%@)",noti.userName,noti.createDate];
	cell.detailTextLabel.text = noti.notificationMsg;
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
	*/
	NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"NotificationCell" owner:nil options:nil];
	NotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		for(id currentObject in topLevelObjects)
		{
			if([currentObject isKindOfClass:[NotificationCell class]])
			{
				cell = (NotificationCell *)currentObject;
			}
		}
		
		NSLog(@"Cell created");
		
		NotificationEntity *noti = [notifications objectAtIndex:[indexPath row]];

		cell.username.text = noti.userName;
		cell.date.text = noti.createDate;
		cell.message.text = noti.notificationMsg;

		if ([NetworkManager activeWLAN]) {
			cell.imageView.image = [UIImage imageNamed:@"profile.png"];
		} else {
			cell.imageView.image = [UIImage imageNamed:@"profile.png"];
		}
	}
	
    return cell;
}

-(void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	// If row is deleted, remove it from the list.
	if (editingStyle == UITableViewCellEditingStyleDelete)
	{
		// delete your data item here
		[EntityManager copyDatabaseIfNeeded];   // check and copy SQL.lite file to Documents folder for use
		EntityManager *entityMgr = [[EntityManager alloc] init];
		[entityMgr removeNotification:[notifications objectAtIndex:indexPath.row]];
		[entityMgr release];
		[notifications removeObjectAtIndex:indexPath.row];
		// Animate the deletion from the table.
		[notificationTableView beginUpdates];
		[notificationTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
		[notificationTableView endUpdates];
	}
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSLog(@"clicked on %d", [indexPath row]);
	// Check if I need to create the instance
	/*
	if (!notificationViewController) {
		notificationViewController = [[NotificationGroupMapViewController alloc] init];
	}
	[notificationViewController setNotification:[notifications objectAtIndex:[indexPath row]]];
	*/
	
	NotificationEntity *note = [notifications objectAtIndex:indexPath.row];
	if (!notificationMap) {
		notificationMap = [[NotificationGroupMapViewController alloc] initWithNotification:note];
	} else {
		[notificationMap setNotification:note];
	}
	[self presentModalViewController:notificationMap animated:YES];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[notificationMap release];
	if (notifications) {
		[notifications release];
	}
    [super dealloc];
}


@end
